package com.springboot.ww.platform.tt.demo;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpRequest;
import com.springboot.ww.platform.tt.api.TikTok2Resp;
import com.springboot.ww.platform.tt.constant.TtApiConstant;
import com.springboot.ww.platform.tt.dto.AuthParamValueVO;
import com.springboot.ww.platform.tt.dto.TikTokTokenRes;
import com.springboot.ww.platform.tt.util.SignUtil;
import com.ww.springboot.boot.utils.json.JsonUtil;

import java.util.*;

import static cn.hutool.core.util.ClassUtil.isSimpleValueType;

/**
 * 描述：
 *
 * @author 🧑 ‍wanwei
 * @since 2024-11-28 14:30
 */
public class Tt2Test {

	public static void main(String[] args) {
		String authParamStr = "{\n" +
			"            \"authId\": \"1777147188644103145\",\n" +
			"            \"platformCode\": \"TT\",\n" +
			"            \"siteCode\": null,\n" +
			"            \"name\": \"shesgirlsmall\",\n" +
			"            \"code\": \"tiktok_0JBV\",\n" +
			"            \"storeStatus\": 1,\n" +
			"            \"token\": \"ROW_fTxMzAAAAABYROx0WHGtiM3KxUv5JFY2IXSoFnQ5NEbeBYm-d2bq4InVhcQMMdWoyxk8hLkzs4RzQzy25WF6V9RkUeLMMRO3ikdaOEq11O38ieC3aoZ2n2vf8TcEKeB73jqMcevLNwmRJMesGlyFXPsiTkjnmSxfoN0Az0b9SaNICfLkCJ03YRoMAMoMwNV5VG2a-u7PC7tU0yowRcP4iY2gGEiTKm8n\",\n" +
			"            \"paramMap\": {\n" +
			"                \"openId\": \"TmKz4AAAAADyGznuZjRJBpFgJX0Ob6Ykob0I5jF141U6JhMmWTRkdg\",\n" +
			"                \"authorizedShop\": \"{\\\"shopList\\\":[{\\\"shopName\\\":\\\"Shesgirlsmall\\\",\\\"type\\\":\\\"1\\\",\\\"shopCipher\\\":\\\"ROW_GxfI6AAAAADSCDhcRHDD8A-BDoN12yFW\\\",\\\"shopId\\\":\\\"8647345967687435854\\\",\\\"region\\\":\\\"PH\\\"},{\\\"shopName\\\":\\\"Shesgirlsmall\\\",\\\"type\\\":\\\"1\\\",\\\"shopCipher\\\":\\\"ROW_Mapy3QAAAAAm3o9_K2FUDLqX2s6pqY25\\\",\\\"shopId\\\":\\\"8647344130171569742\\\",\\\"region\\\":\\\"VN\\\"},{\\\"shopName\\\":\\\"Shesgirlsmall\\\",\\\"type\\\":\\\"1\\\",\\\"shopCipher\\\":\\\"ROW_CScE-QAAAADRf9l8OMG4DtAsGazVRlv3\\\",\\\"shopId\\\":\\\"8647344155958937166\\\",\\\"region\\\":\\\"SG\\\"},{\\\"shopName\\\":\\\"Shesgirlsmall\\\",\\\"type\\\":\\\"1\\\",\\\"shopCipher\\\":\\\"ROW_gDcvkgAAAAA-Nzuj_KoFlYOu_ivIz_Iy\\\",\\\"shopId\\\":\\\"8647344147463702094\\\",\\\"region\\\":\\\"TH\\\"},{\\\"shopName\\\":\\\"Shesgirlsmall\\\",\\\"type\\\":\\\"1\\\",\\\"shopCipher\\\":\\\"ROW_TiXd0QAAAADkMIp-tepqr7tnKrlPAZlF\\\",\\\"shopId\\\":\\\"7495655208088537678\\\",\\\"region\\\":\\\"MY\\\"}]}\",\n" +
			"                \"appSecret\": \"881df98ea9027ce3b6b92fdfebf8b29f6793122d\",\n" +
			"                \"appKey\": \"3a1rgg\"\n" +
			"            },\n" +
			"            \"apiUrl\": \"\"\n" +
			"        }";
		AuthParamValueVO authParamValueVO = JsonUtil.parse(authParamStr, AuthParamValueVO.class);
		String token = authParamValueVO.getToken();
		String country = "MY";
		String propStr = "{\n" +
			"    \"host\": \"http://open-api.tiktokglobalshop.com\",\n" +
			"    \"shippingApi\": \"/fulfillment/202309/packages/ship\",\n" +
			"    \"orderDetailApi\": \"/order/202309/orders\",\n" +
			"    \"labelApi\": \"/fulfillment/202309/packages/%s/shipping_documents\"\n" +
			"}";
		System.out.println(propStr);

		// tiktok 平台每个接口需要传shopId  根据站点来选择
		String authorizedShop = authParamValueVO.getParamMap().get("authorizedShop");
		TikTokTokenRes tikTokTokenRes = JsonUtil.parse(authorizedShop, TikTokTokenRes.class);
		Optional.ofNullable(tikTokTokenRes).orElseThrow(() -> new RuntimeException("TikTok 平台获取店铺 shopId为空"));
		tikTokTokenRes.setShopId(country);
		tikTokTokenRes.setToken(token);
		tikTokTokenRes.setAppKey(authParamValueVO.getParamMap().get("appKey"));
		tikTokTokenRes.setAppSecret(authParamValueVO.getParamMap().get("appSecret"));
	}

	private static void label(String packageId, TikTokTokenRes tikTokTokenRes) {
		String api = String.format(TtApiConstant.LABEL_URL, packageId);
		Map<String, Object> map = new HashMap<>();
		map.put("document_type", "SHIPPING_LABEL");
		String url = SignUtil.getUrl(TtApiConstant.HOST, api, tikTokTokenRes, map);
		String body = HttpRequest.get(url)
			.header("x-tts-access-token", tikTokTokenRes.getToken())
			.execute()
			.body();
		System.out.println(body);
		TikTok2Resp tikTokResp = JsonUtil.parse(body, TikTok2Resp.class);
		String docUrl = tikTokResp.getData().getDocUrl();
		//tiktok 面单生成可能有点慢 需要加个休眠等待
		try {
			Thread.sleep(2000);
		} catch (Exception e) {
			e.printStackTrace();
		}
		byte[] bytes = HttpRequest.get(docUrl).execute().bodyBytes();
		if (bytes.length == 0) {
			if(!tikTokResp.getData().getDocUrl().startsWith("https")){
				docUrl = tikTokResp.getData().getDocUrl().replace("http", "https");
			}
			bytes = HttpRequest.get(docUrl).execute().bodyBytes();
		}
		FileUtil.writeBytes(bytes,"D:\\MyFile\\ZJ00014\\zj014\\Desktop\\test\\" + packageId + ".pdf");
	}

	private static void rts(String packageId,TikTokTokenRes tokenRes) {
		String shippingBody = String.format("{\n" +
			"  \"packages\": [\n" +
			"    {\n" +
			"      \"handover_method\": \"PICKUP\",\n" +
			"      \"id\": \"%s\"\n" +
			"    }\n" +
			"  ]\n" +
			"}", packageId);
		String shippingUrl = SignUtil.getUrl(TtApiConstant.HOST,TtApiConstant.SHIPPING_API, tokenRes,shippingBody);
		System.out.println(shippingUrl);
		String shippingResponse = HttpRequest
			.post(shippingUrl)
			.header("content-type", "application/json")
			.header("x-tts-access-token", tokenRes.getToken())
			.body(shippingBody)
			.execute()
			.body();
		TikTok2Resp tikTok2Resp = JsonUtil.parse(shippingResponse, TikTok2Resp.class);
		System.out.println(JsonUtil.toJson(tikTok2Resp));
	}

	private static TikTok2Resp orderDetail(TikTokTokenRes tikTokTokenRes, String platOrderId) {
		Map<String, Object> map = new LinkedHashMap<>(16);
		map.put("ids", Arrays.asList(platOrderId));
		String orderUrl = SignUtil.getUrl(TtApiConstant.HOST, TtApiConstant.ORDER_DETAIL_API, tikTokTokenRes, map);

		System.out.println(orderUrl);
		String body = HttpRequest.get(orderUrl)
			.header("x-tts-access-token", tikTokTokenRes.getToken())
			.execute()
			.body();
		System.out.println(body);
		TikTok2Resp tikTok2Resp = JsonUtil.parse(body, TikTok2Resp.class);
		return tikTok2Resp;
	}

	private static String getUrlParam(Map<String, Object> authListMap) {
		StringBuilder urlText = new StringBuilder();
		urlText.append("?");
		authListMap.forEach((k, v) -> {
			urlText.append(k).append("=");
			if (isSimpleValueType(v.getClass())) {
				urlText.append(v);
			} else {
				urlText.append(JsonUtil.toJson(v));
			}
			;
			urlText.append("&");
		});
		return urlText.substring(0, urlText.length() - 1);
	}

}
